﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Utils;

namespace Combat
{
    public class BulletsPool : MonoBehaviour
    {
        private const string PlayerBulletLayer = "PlayerBullet";
        private const string EnemyBulletLayer = "EnemyBullet";
        
        public static BulletsPool Instance { get; private set; }

        [SerializeField] private Bullet bulletPrefab;

        [SerializeField] private int defaultSize = 20;
        [SerializeField] private int maxSize = 100;
        
        private ObjectPool<Bullet> _bulletPool;
        

        private void Awake()
        {
            Instance = this;

            _bulletPool = new ObjectPool<Bullet>(bulletPrefab, defaultSize, maxSize);
        }

        public Bullet CreateBullet(Team bulletType, BulletData bulletData, Vector3 startPosition, Vector3 shootDirection)
        {
            Bullet bullet = _bulletPool.Get();
            bullet.gameObject.layer = bulletType switch
            {
                Team.Player => LayerMask.NameToLayer(PlayerBulletLayer),
                Team.Enemy => LayerMask.NameToLayer(EnemyBulletLayer),
                _ => throw new ArgumentOutOfRangeException(nameof(bulletType), bulletType, null)
            };
            
            bullet.Setup(bulletData, startPosition, shootDirection, ReleaseBullet);
            return bullet;
        }

        private void ReleaseBullet(Bullet bullet)
        {
            _bulletPool.Release(bullet);
        }
    }
}